<template>
  <view class="billing-container">
    <!-- 顶部导航栏 -->
    <view class="tab-nav">
      <view 
        class="tab-item" 
        :class="{ active: currentTab === 'recording' }"
        @click="switchTab('recording')"
      >
        记账中
      </view>
      <view 
        class="tab-item" 
        :class="{ active: currentTab === 'pending' }"
        @click="switchTab('pending')"
      >
        待支付
      </view>
      <view 
        class="tab-item" 
        :class="{ active: currentTab === 'completed' }"
        @click="switchTab('completed')"
      >
        已完结
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view
      class="content-area"
      scroll-y
      lower-threshold="50"
      enable-back-to-top
      :scroll-top="scrollTop"
      @scrolltolower="loadMoreProducts"
      @scroll="onScroll"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 内容 -->
      <view  class="tab-content">
        <!-- 加载状态 -->
        <view class="loading-state" v-if="loading && filterDataList.length === 0">
          <text class="loading-text">正在加载记账中数据...</text>
        </view>
        
        <view v-if="!loading && filterDataList.length === 0" class="empty-state">
          <text class="empty-text">暂无记账中的账单</text>
        </view>
        <view v-else-if="filterDataList.length > 0" class="product-list">
          <view v-for="item in filterDataList" :key="item.id" class="product-item">
            <view class="item-header">
              <text class="order-no">{{ item['6881d54f853d0deec0d950f4'] || item['订单号'] }}</text>
              <text class="status-tag recording">{{item['6881cc41853d0deec0d94bc4']}}</text>
            </view>
            <view class="item-content">
              <text class="total-amount">总金额: ¥{{ item['6863789a87058ae1c65da349'] || item['总金额'] }}</text>
            </view>
            <view class="item-footer">
              <text class="create-time">账单日期: {{ item['688ad57d2017d222e26dc814'] || item['账单日期'] }}</text>
            </view>
              <view class="item-footer">
              <text class="create-time">结账日期: {{ item['688ad29a2017d222e26dc64f'] || item['结账日期'] }}</text>
            </view>
          </view>
          
          <!-- 加载更多提示 -->
          <view class="load-more" v-if="filterDataList.length > 0">
            <text class="load-more-text" v-if="loadingMore">正在加载更多...</text>
            <text class="load-more-text" v-else-if="noMoreData">没有更多数据了</text>
            <text class="load-more-text" v-else-if="loadMoreError" @click="loadMoreProducts">加载失败，点击重试</text>
          </view>
        </view>
      </view>

    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import http from '../../../utils/request'
import { callWorkflowListAPI, callWorkflowAPI, callWorkflowListAPIPaged } from '../../../utils/workflow'
import { useUserStore } from '../../../store/user'
import { onLoad, onReady, onUnload, onShow, onBackPress } from '@dcloudio/uni-app'
import { useTaskStore } from '../../../store/task'

const userStore = useUserStore()

const dataList = ref([])

// 当前选中的tab
const currentTab = ref('recording')

const filterDataList = computed(() => {
  // 获取用户所属的供应商ID数组
  const userSupplierIds = userStore.getUserInfo()['68ea18b6470b6cef2f580870'] || []
  
  // 先按状态过滤
  let filteredByStatus = []
  if(currentTab.value === 'recording'){
    filteredByStatus = dataList.value.filter(item => {
      const status = item['6881cc41853d0deec0d94bc4'] || item.status || item['状态']
      return status === '记账中' || status === 'recording'
    })
  }else if(currentTab.value === 'pending'){
    filteredByStatus = dataList.value.filter(item => {
      const status = item['6881cc41853d0deec0d94bc4'] || item.status || item['状态']
      return status === '待支付' || status === 'pending'
    })
  }else if(currentTab.value === 'completed'){
    filteredByStatus = dataList.value.filter(item => {
      const status = item['6881cc41853d0deec0d94bc4'] || item.status || item['状态']
      return status === '已完结' || status === 'completed'
    })
  }
  
  // 再按供应商过滤
  if (!userSupplierIds || userSupplierIds.length === 0) {
    return filteredByStatus // 如果用户没有关联供应商，则返回所有状态过滤后的数据
  }
  
  return filteredByStatus.filter(item => {
    try {
      // 检查账单是否有供应商数据字段
      if (item['6865f5e657603df8e65ce6ab']) {
        // 解析供应商数据
        const supplierData = JSON.parse(JSON.parse(item['6865f5e657603df8e65ce6ab'])[0]['sourcevalue'])
        const billSupplierId = supplierData.rowid
        
        // 检查账单的供应商ID是否在用户的供应商ID数组中
        return userSupplierIds.includes(billSupplierId)
      }
      return false // 如果账单没有供应商数据，则过滤掉
    } catch (error) {
      console.error('解析供应商数据失败:', error)
      return false // 解析出错时过滤掉该条数据
    }
  })
})


// 假数据 - 记账中
const recordingList = ref([
  {
    id: 1,
    orderNo: 'JZ20241201001',
    productName: '商品A',
    quantity: 100,
    unitPrice: 25.5,
    totalAmount: 2550,
    createTime: '2024-12-01 10:30:00',
    status: 'recording'
  },
  {
    id: 2,
    orderNo: 'JZ20241201002',
    productName: '商品B',
    quantity: 50,
    unitPrice: 45.0,
    totalAmount: 2250,
    createTime: '2024-12-01 11:15:00',
    status: 'recording'
  },
  {
    id: 3,
    orderNo: 'JZ20241201003',
    productName: '商品C',
    quantity: 200,
    unitPrice: 12.8,
    totalAmount: 2560,
    createTime: '2024-12-01 14:20:00',
    status: 'recording'
  },
  {
    id: 1,
    orderNo: 'JZ20241201001',
    productName: '商品A',
    quantity: 100,
    unitPrice: 25.5,
    totalAmount: 2550,
    createTime: '2024-12-01 10:30:00',
    status: 'recording'
  },
  {
    id: 2,
    orderNo: 'JZ20241201002',
    productName: '商品B',
    quantity: 50,
    unitPrice: 45.0,
    totalAmount: 2250,
    createTime: '2024-12-01 11:15:00',
    status: 'recording'
  },
  {
    id: 3,
    orderNo: 'JZ20241201003',
    productName: '商品C',
    quantity: 200,
    unitPrice: 12.8,
    totalAmount: 2560,
    createTime: '2024-12-01 14:20:00',
    status: 'recording'
  },
  {
    id: 1,
    orderNo: 'JZ20241201001',
    productName: '商品A',
    quantity: 100,
    unitPrice: 25.5,
    totalAmount: 2550,
    createTime: '2024-12-01 10:30:00',
    status: 'recording'
  },
  {
    id: 2,
    orderNo: 'JZ20241201002',
    productName: '商品B',
    quantity: 50,
    unitPrice: 45.0,
    totalAmount: 2250,
    createTime: '2024-12-01 11:15:00',
    status: 'recording'
  },
  {
    id: 3,
    orderNo: 'JZ20241201003',
    productName: '商品C',
    quantity: 200,
    unitPrice: 12.8,
    totalAmount: 2560,
    createTime: '2024-12-01 14:20:00',
    status: 'recording'
  }
])

// 假数据 - 待支付
const pendingList = ref([
  {
    id: 4,
    orderNo: 'JZ20241201004',
    productName: '商品D',
    quantity: 80,
    unitPrice: 35.6,
    totalAmount: 2848,
    createTime: '2024-12-01 09:00:00',
    status: 'pending'
  },
  {
    id: 5,
    orderNo: 'JZ20241201005',
    productName: '商品E',
    quantity: 150,
    unitPrice: 18.9,
    totalAmount: 2835,
    createTime: '2024-12-01 13:45:00',
    status: 'pending'
  }
])

// 假数据 - 已完结
const completedList = ref([
  {
    id: 6,
    orderNo: 'JZ20241201006',
    productName: '商品F',
    quantity: 120,
    unitPrice: 28.3,
    totalAmount: 3396,
    createTime: '2024-11-30 16:30:00',
    status: 'completed',
    completeTime: '2024-12-01 10:00:00'
  },
  {
    id: 7,
    orderNo: 'JZ20241201007',
    productName: '商品G',
    quantity: 75,
    unitPrice: 42.5,
    totalAmount: 3187.5,
    createTime: '2024-11-30 14:20:00',
    status: 'completed',
    completeTime: '2024-12-01 09:30:00'
  },
  {
    id: 8,
    orderNo: 'JZ20241201008',
    productName: '商品H',
    quantity: 90,
    unitPrice: 22.1,
    totalAmount: 1989,
    createTime: '2024-11-30 11:10:00',
    status: 'completed',
    completeTime: '2024-11-30 17:45:00'
  }
])

const statusMap = {
  recording: '记账中',
  pending: '待支付',
  completed: '已完结'
}

// 分页参数
const pageIndex = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 加载状态
const loading = ref(false)
const loadingMore = ref(false)
const noMoreData = ref(false)
const loadMoreError = ref(false)
const refreshing = ref(false)

// 滚动位置
const scrollTop = ref(0)

// 切换tab
const switchTab = (tab) => {
  currentTab.value = tab
  // 切换tab时重置分页状态
  pageIndex.value = 1
  noMoreData.value = false
  loadMoreError.value = false
  // 重新加载当前tab的数据
  getDataList()
}

// 滚动事件处理
const onScroll = (e) => {
  scrollTop.value = e.detail.scrollTop
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  pageIndex.value = 1
  noMoreData.value = false
  loadMoreError.value = false
  scrollTop.value = 0
  getDataList(true)
}

// 上拉加载更多
const loadMoreProducts = () => {
  console.log('加载更多账单数据');
  if (loadingMore.value || noMoreData.value || loadMoreError.value) {
    return
  }
  
  // 添加防抖处理，避免频繁触发
  setTimeout(() => {
    loadMoreData()
  }, 300)
}

// 独立的加载更多数据方法
const loadMoreData = async () => {
  try {
    loadingMore.value = true
    loadMoreError.value = false
    
    // 计算下一页的页码
    const nextPageIndex = pageIndex.value + 1
    
    const result = await callWorkflowListAPIPaged('6863789a87058ae1c65da346', [{
          "controlId": "6881cc41853d0deec0d94bc4",
          "dataType": 30,
          "spliceType": 1,
          "filterType": 2,
          "values": [statusMap[currentTab.value]]
        }], pageSize.value, nextPageIndex, 0)
    
    if(result && result.data) {
      console.log('加载更多账单数据:', result.data)
      
      // 追加数据到现有列表
      if (result.data.length > 0) {
        dataList.value = [...dataList.value, ...result.data]
        // 只有在数据加载成功后才更新页码
        pageIndex.value = nextPageIndex
      }
      
      // 检查是否还有更多数据
      if (result.data.length < pageSize.value || dataList.value.length >= result.totalCount) {
        noMoreData.value = true
      }
      
    } else {
      loadMoreError.value = true
    }
  } catch (error) {
    console.error('加载更多账单数据失败:', error)
    loadMoreError.value = true
  } finally {
    loadingMore.value = false
  }
}

const getDataList = async (isRefresh = false) => {
  try {
    if (isRefresh) {
      refreshing.value = true
    } else {
      loading.value = true
    }
    
    const result = await callWorkflowListAPIPaged('6863789a87058ae1c65da346', [{
          "controlId": "6881cc41853d0deec0d94bc4",
          "dataType": 30,
          "spliceType": 1,
          "filterType": 2,
          "values": [statusMap[currentTab.value]]
        }], pageSize.value, 1, 0)
    
    if(result && result.data){
      console.log('账单数据:', result.data)
      
      if (isRefresh) {
        // 刷新时重置数据
        dataList.value = result.data
      } else {
        // 初始加载或加载更多
        if (pageIndex.value === 1) {
          dataList.value = result.data
        } else {
          dataList.value = [...dataList.value, ...result.data]
        }
      }
      
      totalCount.value = result.totalCount
      
      // 检查是否还有更多数据
      if (result.data.length < pageSize.value || dataList.value.length >= result.totalCount) {
        noMoreData.value = true
      }
      
    } else {
      uni.showToast({
        title: '获取账单数据失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取账单数据失败:', error)
    uni.showToast({
      title: '获取账单数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}


// 重置数据
const resetData = () => {
  dataList.value = []
  pageIndex.value = 1
  totalCount.value = 0
  noMoreData.value = false
  loadMoreError.value = false
  scrollTop.value = 0
}



onLoad( () => {
   resetData()
   getDataList()
})

</script>

<style lang="scss" scoped>
.billing-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .tab-nav {
    display: flex;
    background-color: #fff;
    border-bottom: 1px solid #e5e5e5;
    position: sticky;
    top: 0;
    z-index: 100;
    
    .tab-item {
      flex: 1;
      text-align: center;
      padding: 30rpx 0;
      font-size: 28rpx;
      color: #666;
      position: relative;
      transition: all 0.3s ease;
      
      &.active {
        color: #007aff;
        font-weight: 500;
        
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 60rpx;
          height: 4rpx;
          background-color: #007aff;
          border-radius: 2rpx;
        }
      }
    }
  }
  
  .content-area {
    padding: 20rpx;
    height: calc(100vh - 200rpx); // 减去顶部标签栏高度
    
    .tab-content {
      min-height: 400rpx;
      
      .loading-state {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 400rpx;
        background-color: #fff;
        border-radius: 16rpx;
        margin: 20rpx 0;
        
        .loading-text {
          color: #666;
          font-size: 28rpx;
        }
      }
      
      .empty-state {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 400rpx;
        background-color: #fff;
        border-radius: 16rpx;
        margin: 20rpx 0;
        
        .empty-text {
          color: #999;
          font-size: 28rpx;
        }
      }
      
      .product-list {
        .product-item {
          background-color: #fff;
          border-radius: 16rpx;
          padding: 30rpx;
          margin-bottom: 20rpx;
          box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
          
          .item-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20rpx;
            
            .order-no {
              font-size: 28rpx;
              font-weight: 500;
              color: #333;
            }
            
            .status-tag {
              padding: 8rpx 16rpx;
              border-radius: 20rpx;
              font-size: 24rpx;
              font-weight: 500;
              
              &.recording {
                background-color: #e3f2fd;
                color: #1976d2;
              }
              
              &.pending {
                background-color: #fff3e0;
                color: #f57c00;
              }
              
              &.completed {
                background-color: #e8f5e8;
                color: #388e3c;
              }
            }
          }
          
          .item-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16rpx;
            margin-bottom: 20rpx;
            
            
            .total-amount {
              color: #ff5722;
              font-weight: 600;
            }
          }
          
          .item-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-top: 20rpx;
            border-top: 1rpx solid #f0f0f0;
            
            .create-time, .complete-time {
              font-size: 24rpx;
              color: #999;
            }
          }
        }
        
        .load-more {
          display: flex;
          justify-content: center;
          align-items: center;
          padding: 30rpx 0;
          
          .load-more-text {
            font-size: 26rpx;
            color: #999;
            
            &:active {
              opacity: 0.7;
            }
          }
        }
      }
    }
  }
}
</style>